home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 406 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.8 KB  |  51 lines

  1. Path: sun001.spd.dsccc.com!spd!jmccarty
  2. From: jmccarty@spd.dsccc.com (Mike McCarty)
  3. Newsgroups: comp.lang.c,comp.std.c,comp.lang.c++
  4. Subject: Re: Floating Point arithmetic problem
  5. Date: 15 Feb 1996 19:11:17 GMT
  6. Organization: DSC Communications Corporation, Plano, Texas USA
  7. Message-ID: <4g00gl$g83@sun001.spd.dsccc.com>
  8. References: <c968da6jzm.fsf@damayanti.india.ti.com>
  9. NNTP-Posting-Host: aplo139.spd.dsccc.com
  10.  
  11. In article <c968da6jzm.fsf@damayanti.india.ti.com>,
  12. Kuntal Shah <kuntal@india.ti.com> wrote:
  13. )
  14. )I am having a wierd problem with floating point arithmetic. Gurus on
  15. )the net, please bail me out. I am working on the SUN 4.1.x platform.
  16. )
  17. )I have a "double" variable say d to which  I need to add certain float
  18. )numbers  of  moderate magnitude (say   less than 10000). This addition
  19. )occurs in a loop in my program which  get executed more than a million
  20. )times depending on my testcase.
  21.  
  22. [stuff cut]
  23.  
  24. )This addition  usually results in  a  few insignificant digits getting
  25. )accumulated in my double variable. For eg.
  26. )
  27. )  f = 12.99  is represented as 12.9900000000000002131628207
  28. )  f = 11.111 is represented as 11.1110000000000006536993169
  29. )
  30. )and so on. I am interested in comparisons with 4 digits precision.
  31. )
  32. )Now coming  to   the  problem. The  insignificant  digits   due to the
  33. )floating  point representation keep  accruing and  there comes a stage
  34. )when the accrued value exceeds 0.0001 which  results in failure of the
  35. )if condition in the  above block of code,  when ideally no such  thing
  36. )should have occurred.
  37.  
  38. [stuff cut]
  39.  
  40. Every 1000 or 10000 or whatever, do a roundoff. Easiest way is:
  41.  
  42.     #define FACTOR    1e4
  43.  
  44.     d = floor(d*FACTOR+0.5)/FACTOR;
  45.  
  46. Mike
  47. ----
  48. char *p="char *p=%c%s%c;main(){printf(p,34,p,34);}";main(){printf(p,34,p,34);}
  49.  
  50. I don't speak for DSC.         <- They make me say that.
  51.